package com.csdj.server.conflg;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author xyx
 * @Date 2022/12/14 10:33
 * @ClassName: JwtAuthenticationTokenFilter
 * @Description: Jwt 过滤器
 * @Version 1.0
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //请求拦截处理 用户请求是否携带token信息
        //通过 http请求 拿去 请求头信息
        String header = request.getHeader(this.tokenHeader);
        if(header!=null && header.startsWith(this.tokenHead)){
            //截取token
            String authToken = header.substring(this.tokenHead.length());
            //根据token 获取用户名
            String username = jwtTokenUtil.getUserNameFormToken(authToken);
            //用户名 存在 但是 授权管理中心没有 授权信息
            //SecurityContextHolder.getContext().getAuthentication() 获取授权信息
            if(username!=null && SecurityContextHolder.getContext().getAuthentication()==null){
                //重新加载 登录逻辑
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //验证token是否失效 重新设置 用户对象
                if(jwtTokenUtil.validateToken(authToken,userDetails)){
                    //设置 用户对象 UsernamePasswordAuthenticationToken(1.用户信息 2.null 3.用户权限)
                    UsernamePasswordAuthenticationToken
                            authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    //设置 请求 重新 构建加载 资源信息
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    //重新设置到 Security的全局实例中
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        //通过过滤
        filterChain.doFilter(request,response);
    }
}
